package com.gdssoft.pdaweb.action.am;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.gdssoft.core.command.QueryFilter;
import com.gdssoft.core.util.BeanUtil;
import com.gdssoft.core.util.ContextUtil;
import com.gdssoft.core.util.DateUtil;
import com.gdssoft.core.util.JsonUtil;
import com.gdssoft.core.web.action.BaseAction;
import com.gdssoft.framework.model.system.AppUser;
import com.gdssoft.pdaweb.model.PdaMdBuilding;
import com.gdssoft.pdaweb.model.PdaMdDistrict;
import com.gdssoft.pdaweb.model.am.AmMonthPlan;
import com.gdssoft.pdaweb.model.am.AmMonthPlanRead;
import com.gdssoft.pdaweb.model.am.AmPlan;
import com.gdssoft.pdaweb.model.am.PdaAmMeter;
import com.gdssoft.pdaweb.service.am.AmMonthPlanService;
import com.gdssoft.pdaweb.service.am.AmPlanService;
import com.gdssoft.pdaweb.service.am.PdaAmMeterService;

import com.gdssoft.pdaweb.service.PdaMdBuildingService;
import com.gdssoft.pdaweb.service.PdaMdDistrictService;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ibm.icu.text.SimpleDateFormat;

import flexjson.JSONSerializer;

public class AmPlanAction extends BaseAction {
	
	@Resource
	private AmPlanService amPlanService;
	
	@Resource
	private PdaAmMeterService pdaAmMeterService;

	private AmPlan amPlan;

	private Long planId;

	@Resource
	private AmMonthPlanService amMonthPlanService;

//	@Resource
//	private PdaAmService pdaAmService;
//
	@Resource
	private PdaMdDistrictService pdaMdDistrictService;

	@Resource
	private PdaMdBuildingService pdaMdBuildingService;
	

	public Long getPlanId() {
		return planId;
	}

	public void setPlanId(Long planId) {
		this.planId = planId;
	}

	public AmPlan getAmPlan() {
		return amPlan;
	}

	public void setAmPlan(AmPlan amPlan) {
		this.amPlan = amPlan;
	}

	public PdaAmMeterService getPdaAmMeterService() {
		return pdaAmMeterService;
	}

	public void setPdaAmMeterService(PdaAmMeterService pdaAmMeterService) {
		this.pdaAmMeterService = pdaAmMeterService;
	}

	public PdaMdBuildingService getPdaMdBuildingService() {
		return pdaMdBuildingService;
	}

	public void setPdaMdBuildingService(PdaMdBuildingService pdaMdBuildingService) {
		this.pdaMdBuildingService = pdaMdBuildingService;
	}

	public PdaMdDistrictService getPdaMdDistrictService() {
		return pdaMdDistrictService;
	}

	public void setPdaMdDistrictService(PdaMdDistrictService pdaMdDistrictService) {
		this.pdaMdDistrictService = pdaMdDistrictService;
	}

	public AmPlanService getAmPlanService() {
		return amPlanService;
	}

	public void setAmPlanService(AmPlanService amPlanService) {
		this.amPlanService = amPlanService;
	}

	
	public AmMonthPlanService getAmMonthPlanService() {
		return amMonthPlanService;
	}

	public void setAmMonthPlanService(AmMonthPlanService amMonthPlanService) {
		this.amMonthPlanService = amMonthPlanService;
	}

	/**
	 * 显示列表
	 */
	public String list() {

		QueryFilter filter = new QueryFilter(getRequest());
		filter.addSorted("planStatus", QueryFilter.ORDER_DESC);
		filter.addSorted("planName", QueryFilter.ORDER_ASC);
		List<AmPlan> list = amPlanService.getAll(filter);
		
		int toDayDate = Calendar.getInstance().get(Calendar.DATE);
		String thisMonth = DateUtil.dateFormat(new Date(), "yyyy-MM");
		AmMonthPlan monthPlan = null;
		for(AmPlan p :list){
			if(toDayDate > Integer.parseInt(p.getAccountDay())){	//过了月结日
				p.setPlanStatus(0L);
			}else{
				monthPlan = amMonthPlanService.getByPlanIdAndMonth(p.getPlanId(),thisMonth);
				if(monthPlan != null && monthPlan.getPlanStatus()==0L){
					//当状态是执行过的，设置为2
					p.setPlanStatus(2L);
				}
			}
		}
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
				.append(filter.getPagingBean().getTotalItems()).append(
						",result:");

		Type type = new TypeToken<List<AmPlan>>() {
		}.getType();
		Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
				.setDateFormat("yyyy-MM-dd").create();
		buff.append(gson.toJson(list, type));

		buff.append("}");
		jsonString = buff.toString();

		return SUCCESS;
	}

	/**
	 * 批量删除
	 * 
	 * @return
	 */

	public String multiDel() {

		String[] ids = getRequest().getParameterValues("ids");
		if (ids != null) {
			for (String id : ids) {
				try {
					this.amPlanService.remove(new Long(id));
				} catch (NumberFormatException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}
		jsonString = "{success:true}";
		return SUCCESS;
	}

	/**
	 * 显示详细信息
	 * 
	 * @return
	 */
	public String get() {
		// deviceId =
		// Long.parseLong(getRequest().getParameterValues("deviceId")[0]);
		// DeviceReg deviceReg=deviceRegService.get(deviceId);
		// //Gson gson = new
		// GsonBuilder().excludeFieldsWithoutExposeAnnotation().setDateFormat("yyyy-MM-dd").create();
		// Gson gson = new
		// GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
		// //将数据转成JSON格式
		// StringBuffer sb = new StringBuffer("{success:true,data:");
		// sb.append(gson.toJson(deviceReg));
		// sb.append("}");
		//
		// setJsonString(sb.toString());
		return SUCCESS;
	}

	/**
	 * 添加及保存操作
	 */
	public String save() {
		/*String removedStr = getRequest().getParameter("removed");
		String[] removeds = removedStr.split(",");
		String amIdss = getRequest().getParameter("amIds");
		String[] amIds = amIdss.split(",");*/
		
		String removedStr = getRequest().getParameter("removed");
		String[] removeds = {};
		if(!removedStr.trim().isEmpty()){
			removeds = removedStr.split(",");
		}		
		String amIdss = getRequest().getParameter("amIds");
		String[] amIds = {};
		if(!amIdss.trim().isEmpty()){
			amIds = amIdss.split(",");
		}
		
		
		boolean success = true;
		if (amIds.length == 0) {
			success = false;
		} else {
			String un = ContextUtil.getCurrentUser().getUsername();
			Date now = new Date();
			if (amPlan.getPlanId() == null) {
				amPlan.setCreatedBy(un);
				amPlan.setCreatedDt(now);
				amPlan.setPlanStatus((long) 0);
			} else {
				AmPlan plan = amPlanService.get(amPlan.getPlanId());
				try {
					BeanUtil.copyNotNullProperties(plan, amPlan);
				} catch (Exception e) {
					success = false;
				}
				amPlan = plan;
				amPlan.setLastEditDt(now);
				amPlan.setLastEditBy(un);
			}
			amPlan.setMeterCount(new Long(amIds.length));
			try {
				amPlanService.save(amPlan, amIds,removeds);
			} catch (Exception e) {
				success = false;
				e.printStackTrace();
			}
		}
		setJsonString("{success:" + success + "}");
		return SUCCESS;
	}

	/**
	 * 执行计划
	 */
	public String execute() {
		String username = getRequest().getParameter("username");
		String planId = getRequest().getParameter("planId");
		String beginTime = getRequest().getParameter("beginTime");
		String endTime = getRequest().getParameter("endTime");

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date beginTime2 = new Date();
		Date endTime2 = new Date();
		try {
			beginTime2 = sdf.parse(beginTime);
			endTime2 = sdf.parse(endTime);
		} catch (ParseException e) {
			logger.debug("日期转换出错,beginTime:" + beginTime + ",endTime:"
					+ endTime);
			e.printStackTrace();
		}
		boolean res = amPlanService.execute(Long.parseLong(planId),beginTime2, endTime2, username);

		jsonString = "{success:" + res + "}";

		return SUCCESS;
	}

	/**
	 * 显示抄表人姓名
	 */
	public String showExecutorName() {

		List<AppUser> ls = amPlanService.getExecutor();
		StringBuffer buff = new StringBuffer("[");
		for (AppUser appUser : ls) {
			buff.append("[\"" + appUser.getUsername() + "\",\""
					+ appUser.getFullname() + "(" + appUser.getUsername()
					+ ")\"],");
		}
		buff.deleteCharAt(buff.length() - 1);
		buff.append("]");

		setJsonString(buff.toString());

		return SUCCESS;
	}

	/**
	 * 通过Id获取相应的水表号
	 */
	public String getByPlanId() {
		System.out.println("***********planId********"+planId);
		List<String> amIds = amPlanService.getByPlanId(planId);
		StringBuffer buff = new StringBuffer("[");
		for (String id : amIds) {
			buff.append("[\"" + id + "\",\"" + id + "\"],");
		}
		buff.deleteCharAt(buff.length() - 1);
		buff.append("]");
		setJsonString(buff.toString());

		return SUCCESS;

	}

	/**
	 * 显示水表编号
	 */
	public String getAmId() {
		String districtId = getRequest().getParameter("districtId");
		String buildingId = getRequest().getParameter("buildingId");
		
		List<PdaAmMeter> ls = pdaAmMeterService.getAm(districtId,buildingId);
		if (ls.size() > 0) {
			StringBuffer buff = new StringBuffer("[");
			for (PdaAmMeter pdaAmMeter : ls) {
				buff.append("[\"" + pdaAmMeter.getAmId() + "\",\""
						+ pdaAmMeter.getAmId() + "\"],");
			}
			buff.deleteCharAt(buff.length() - 1);
			buff.append("]");
			setJsonString(buff.toString());
		} else {
			setJsonString("[]");
		}
		return SUCCESS;
	}

	/**
	 * 查看任务
	 */
	public String checkTask() {
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

		String planId = getRequest().getParameter("planId");
		String month = getRequest().getParameter("month");

		List<AmMonthPlanRead> ls = amPlanService.getPlanTask(Long.parseLong(planId), month);

		StringBuffer buff = new StringBuffer("{success:true,'result':");

		JSONSerializer json = JsonUtil.getJSONSerializer();
		buff.append(json.exclude(new String[] { "class", "AmMonthPlanRead" }).serialize(ls));
		buff.append("}");

		jsonString = buff.toString();
		return SUCCESS;
	}

	/**
	 * 显示区号信息
	 */
	public String showDistrict() {
		List<PdaMdDistrict> ls = pdaMdDistrictService.getAll();
		StringBuffer buff = new StringBuffer("[");
		for (PdaMdDistrict pdaMdDistrict : ls) {
			buff.append("[\"" + pdaMdDistrict.getDistrictId() + "\",\""
					+ pdaMdDistrict.getDistrictName() + "\"],");
		}
		buff.deleteCharAt(buff.length() - 1);
		buff.append("]");

		setJsonString(buff.toString());
		return SUCCESS;
	}

	/**
	 * 显示栋号信息
	 */
	public String showBuilding() {
		String districtId = getRequest().getParameter("districtId");
		List<PdaMdBuilding> ls = pdaMdBuildingService
				.getByDistrictId(districtId);

		StringBuffer buff = new StringBuffer("[");
		for (PdaMdBuilding pdaMdBuilding : ls) {
			buff.append("[\"" + pdaMdBuilding.getBuildingId() + "\",\""
					+ pdaMdBuilding.getBuildingName() + "\"],");
		}
		buff.deleteCharAt(buff.length() - 1);
		buff.append("]");

		setJsonString(buff.toString());

		return SUCCESS;
	}

}
